<template>
  <div class="ele-body">
    <el-card shadow="never">
      <!-- 搜索表单 -->
      <user-search @search="reload" />
      <!-- 数据表格 -->
      <ele-pro-table ref="table"
                     :columns="columns"
                     :datasource="datasource"
                     cache-key="systemUserTable">
        <!-- 表头工具栏 -->
        <template v-slot:toolbar>

        </template>
        <template v-slot:distributionGrCode="{ row }">
          <el-link type="primary"
                   :underline="false"
                   icon="el-icon-view"
                   @click="openInvoice(row.invite_url)">
            查看
          </el-link>
          <!-- 下载 -->
          <!-- <el-link type="info"
                   :underline="false"
                   icon="el-icon-download"
                   @click="download(row.distributionQrCode)">
            公众号
          </el-link> -->
        </template>
        <template v-slot:nickname="{ row }">
          <div>
            <div class="realNameStyle">
              <img class="avaterName"
                   :src="row.avatar"
                   alt="" />
              <span>{{ row.wachat_nickname }}</span>
            </div>
          </div>

        </template>
        <template v-slot:superiorUser="{ row }">
          <div v-if="row.p_wachat_nickname">
            <div class="realNameStyle">
              <img class="avaterName"
                   :src="row.p_avatar"
                   alt="" />
              <span>{{ row.p_wachat_nickname }}</span>
            </div>
          </div>
          <div v-else>-----</div>
        </template>
        <!-- 用户名列 -->
        <!-- 状态列 -->
        <template v-slot:status="{ row }">
          <el-switch :active-value="1"
                     :inactive-value="0"
                     v-model="row.status"
                     @change="editStatus(row)" />
        </template>
        <!-- 操作列 -->
        <template v-slot:action="{ row }">
          <el-link type="primary"
                   :underline="false"
                   icon="el-icon-edit"
                   @click="openEdit(row)">
            修改上级
          </el-link>
          <el-link type="primary"
                   :underline="false"
                   icon="el-icon-edit"
                   @click="deductionTA(row)">
            扣除TA
          </el-link>
          <el-link type="primary"
                   :underline="false"
                   icon="el-icon-key"
                   @click="balanceRecords(row)">
            余额记录
          </el-link>
          <el-link type="primary"
                   :underline="false"
                   icon="el-icon-key"
                   @click="operationRecords(row)">
            积分记录
          </el-link>
          <el-link type="primary"
                   :underline="false"
                   icon="el-icon-key"
                   @click="commissionRecords(row)">
            佣金记录
          </el-link>
          <el-popconfirm class="ele-action"
                         :title="`确定要${row.status === 0 ? '启动' : '禁用'}该条数据？`"
                         @confirm="remove(row)">
            <template v-slot:reference>
              <el-link type="danger"
                       :underline="false"
                       icon="el-icon-edit">
                {{ row.status==0?'启动':'禁用' }}
              </el-link>
            </template>
          </el-popconfirm>
        </template>
      </ele-pro-table>
    </el-card>
    <!-- 编辑弹窗 -->

    <balanceEdit :data="currentss"
                 :drawerEditBoolens.sync="drawerEditBoolens" />
    <role-edit :data="currents"
               :drawerEditBoolen.sync="drawerEditBoolen" />
    <commissionEdit :data="currentsss"
                    :drawerEditBoolenss.sync="drawerEditBoolenss" />
    <user-edit :visible.sync="showEdit"
               :data="current"
               @done="reload" />
    <!-- 导入弹窗 -->
    <ele-modal width="600px"
               height="300px"
               title="扣除（余额积分佣金）"
               :visible.sync="visibleModalDelivery"
               :maxable="true">
      <!-- class="SigningReminder" -->
      <el-form ref="form"
               :model="form"
               label-width="100px">
        <el-form-item label="扣除的余额:"
                      prop="balance">
          <el-input class="uni-input"
                    v-model="form.balance"
                    placeholder="请输入要扣除的余额"></el-input>
        </el-form-item>
        <el-form-item label="扣除的积分:"
                      prop="surplus_integral">
          <el-input class="uni-input "
                    v-model="form.surplus_integral"
                    placeholder="请输入要扣除的积分"></el-input>
        </el-form-item>

        <el-form-item label="扣除的佣金:"
                      prop="surplus_commission">
          <el-input class="uni-input"
                    v-model="form.surplus_commission"
                    placeholder="请输入要扣除的佣金"></el-input>
        </el-form-item>

      </el-form>

      <span slot="footer"
            class="dialog-footer">
        <el-button @click="visibleModalDelivery=false">取 消</el-button>
        <el-button type="primary"
                   :loading="loading"
                   @click="visibleModalDeliverFn()">确定</el-button>

      </span>
    </ele-modal>

    <el-dialog title="分销海报码"
               style="text-align: center;"
               :visible.sync="dialogVisible"
               width="25%"
               :before-close="handleClose">

      <img class="imgCode"
           :src="qRCode"
           alt="">
      <span slot="footer"
            class="dialog-footer">
        <el-button type="primary"
                   @click="dialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import balanceEdit from './components/balance-edit';
import commissionEdit from './components/commission-edit.vue';
import RoleEdit from './components/role-edit.vue';
import UserSearch from './components/user-search.vue';
import UserEdit from './components/user-edit.vue';
import {
  pageUsers,
  removeUser,
  removeUsers,
  updateUserStatus,
  updateUserPassword,
  setAmount,

} from '@/api/user/user';
// import { status } from 'nprogress';

export default {
  name: 'SystemUser',
  components: {
    UserSearch,
    UserEdit,
    RoleEdit,
    balanceEdit,
    commissionEdit
  },
  data () {
    const defaultWhere = {
      balance: 0,
      surplus_integral: 0,
      id: '',
      type: 2,
      surplus_commission: 0

    };
    return {
      // 表格列配置
      visibleModalDelivery: false,
      columns: [

        {
          columnKey: 'index',
          type: 'index',
          width: 45,
          align: 'center',
          showOverflowTooltip: true,
          fixed: 'left'
        },
        {
          prop: 'nickname',
          label: '昵称',
          align: 'center',
          showOverflowTooltip: false,
          minWidth: 110,
          slot: 'nickname',
        },
        {
          prop: 'phone',
          label: '手机号',
          align: 'center',
          minWidth: 110
        },


        {
          prop: 'level_name',
          label: '会员等级',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 110,

        },
        {
          prop: 'balance',
          label: '余额',
          align: 'center',
          sortable: 'custom',
          showOverflowTooltip: true,
          minWidth: 110,

        },
        {
          prop: 'consumption_amount',
          label: '消费金额',
          sortable: 'custom',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 110,

        },
        {
          prop: 'surplus_commission',
          label: '佣金',
          showOverflowTooltip: true,
          minWidth: 110,
          align: 'center',
        },
        {
          prop: 'real_name',
          label: '真实姓名',
          showOverflowTooltip: true,
          minWidth: 110,
          align: 'center',
        },
        {
          prop: 'surplus_integral',
          label: '积分',
          showOverflowTooltip: true,
          minWidth: 110,
          align: 'center',
        },
        {
          prop: 'superiorUser',
          label: '用户上级',
          align: 'center',
          showOverflowTooltip: false,
          minWidth: 110,
          slot: 'superiorUser',
        },
        {
          prop: 'distributionGrCode',
          label: '分销海报',
          sortable: 'custom',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 210,
          slot: 'distributionGrCode'
        },

        {
          prop: 'create_time',
          label: '创建时间',
          align: 'center',
          sortable: 'custom',
          showOverflowTooltip: false,
          minWidth: 110,
          formatter: (_row, _column, cellValue) => {
            return this.$util.toDateString(cellValue);
          }
        },

        {
          columnKey: 'action',
          label: '操作',
          minWidth: 220,
          align: 'center',
          resizable: false,
          slot: 'action',
          showOverflowTooltip: false
        }
      ],
      // 表格选中数据
      selection: [],
      // 当前编辑数据
      current: null,
      currents: null,
      currentss: null,
      currentsss: null,
      // 是否显示编辑弹窗
      showEdit: false,
      // 是否显示导入弹窗
      showImport: false,
      loading: false,
      drawerEditBoolen: false,
      drawerEditBoolens: false,
      drawerEditBoolenss: false,
      dialogVisible: false,
      qRCode: null,
      form: { ...defaultWhere }
    };
  },
  methods: {

    //    查看海报
    openInvoice (imgStr) {
      // 点击按钮预览图片

      console.log(imgStr);
      this.dialogVisible = true
      this.qRCode = imgStr


    },
    deductionTA (row) {
      this.$util.assignObject(this.form, {
        ...row
      });
      this.visibleModalDelivery = true
    },
    async visibleModalDeliverFn () {
      this.loading = true
      const res = await setAmount({
        balance: this.form.balance,
        integral: this.form.surplus_integral,
        commission: this.form.surplus_commission,
        id: this.form.id,
        type: 2,
      })
      console.log(res.data)
      if (res.code == 0) {
        this.$message.success(res.message);
        this.loading = false
        this.form = { ...this.defaultWhere };
        this.visibleModalDelivery = false,
          this.reload();

      } else {
        this.$message.success(res.message);
      }
    },
    /* 表格数据源 */
    datasource ({ page, limit, where, order }) {
      return pageUsers({ ...where, ...order, page, limit });
    },
    /* 刷新表格 */
    reload (where) {
      this.$refs.table.reload({ page: 1, where: where });
    },
    /* 打开编辑弹窗 */
    openEdit (row) {
      this.current = row;
      this.showEdit = true;
    },
    /* 打开导入弹窗 */
    openImport () {
      this.showImport = true;
    },
    /* 删除 */
    remove (row) {
      console.log(row.status)
      const loading = this.$loading({ lock: true });
      removeUser({
        id: row.id,
        status: row.status == 1 ? 0 : 1
      })
        .then((msg) => {
          loading.close();
          this.$message.success(msg);
          this.reload();
        })
        .catch((e) => {
          loading.close();
          this.$message.error(e.message);
        });
    },
    /* 批量删除 */
    removeBatch () {
      if (!this.selection.length) {
        this.$message.error('请至少选择一条数据');
        return;
      }
      this.$confirm('确定要删除选中的用户吗?', '提示', {
        type: 'warning'
      })
        .then(() => {
          const loading = this.$loading({ lock: true });
          removeUsers(this.selection.map((d) => d.userId))
            .then((msg) => {
              loading.close();
              this.$message.success(msg);
              this.reload();
            })
            .catch((e) => {
              loading.close();
              this.$message.error(e.message);
            });
        })
        .catch(() => { });
    },
    // 操作记录
    operationRecords (row) {
      console.log(row);

      if (row?.id) {
        // const res = await siteCategoriesDetail(row.id);

        this.currents = row;
        // 用户余额管理
        this.drawerEditBoolen = true;
      } else {
        this.drawerEditBoolen = !this.drawerEditBoolen;
        this.currents = null;
      }
    },
    // 余额操作
    balanceRecords (row) {
      if (row?.id) {
        // const res = await siteCategoriesDetail(row.id);

        this.currentss = row;
        // 用户余额管理
        this.drawerEditBoolens = !this.drawerEditBoolens;
      } else {
        this.drawerEditBoolens = !this.drawerEditBoolens;
        this.currentss = null;
      }
    },
    // 佣金记录
    commissionRecords (row) {
      if (row?.id) {
        // const res = await siteCategoriesDetail(row.id);

        this.currentsss = row;
        // 用户余额管理
        this.drawerEditBoolenss = !this.drawerEditBoolenss;
      } else {
        this.drawerEditBoolenss = !this.drawerEditBoolenss;
        this.currentsss = null;
      }
    },
    /* 重置用户密码 */
    resetPsw (row) {
      this.$confirm('确定要重置此用户的密码为123456吗?', '提示', {
        type: 'warning'
      })
        .then(() => {
          const loading = this.$loading({ lock: true });
          updateUserPassword(row.id)
            .then((msg) => {
              loading.close();
              this.$message.success(msg);
            })
            .catch((e) => {
              loading.close();
              this.$message.error(e.message);
            });
        })
        .catch(() => { });
    },
    /* 更改状态 */
    editStatus (row) {
      const loading = this.$loading({ lock: true });
      updateUserStatus(row.id, row.status)
        .then((msg) => {
          loading.close();
          this.$message.success(msg);
        })
        .catch((e) => {
          loading.close();
          row.status = !row.status ? 0 : 1;
          this.$message.error(e.message);
        });
    }
  }
};
</script>
<style scoped lang="less">
.imgCode {
  width: 100%;
  height: 300px;
}
.realNameStyle {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  .avaterName {
    width: 32px;
    height: 32px;
    border-radius: 32px;
    vertical-align: middle;
    margin-right: 5px;
  }
}
</style>
